<template>
  <div class="app-container-flex">
    <NewFullScreen
      v-model="showDialog"
      :title="title"
      :btn-list="fullInfo.btnList"
      @returnBack="$emit('returnModify')"
    >

      <div class="model-panel">
        <div class="model-panel-body">
          <div class="filter-wrapper">
            <!-- 条件栏 -->
            <page-filter
              v-model:query="filterInfo.query"
              :filter-list="filterInfo.list"
            >
              <template v-slot:filter-addProduct>
                <el-button  @click="addProduct"
                  >添加产品</el-button
                >
              </template>
              <template v-slot:filter-removeProduct>
                <el-button
                  :disabled="!canRemoveProduct"
                  @click="removeProduct()"
                  >删除产品</el-button
                >
              </template>
            </page-filter>
            <div class="display-flex">
              <el-button @click="preferenceInfo.visible = true"
                >偏好设置</el-button
              >
            </div>
          </div>
          <div class="flex_full_item">
            <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
              <!-- 表格 -->
              <page-table
                ref="table"
                class="table-scroll-hidden"
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :summary="true"
                :summary-field-list="tableInfo.summaryFieldList"
                :tab-index="false"
                :query="filterInfo.query"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                :row-class-name="tableRowClassName"
                :cell-class-name="tableCellClassName"
                :isDynamic="true"
                @handleEvent="handleEvent"
              >
                <template v-slot:col-qty="scope">
                  <el-form-item class="margin-bottom">
                    <div class="page-table-input-number-wrapper">
                      <div class="page-table-input-number-left">
                        <div class="page-table-input-number-item">
                          <el-form-item
                            :prop="`data.${scope.$index}.largeUnitQty`"
                            :rules="
                              scope.$index >= 0
                                ? [
                                    {
                                      validator: $validate.positiveAndZero,
                                      trigger: 'blur',
                                    },
                                  ]
                                : []
                            "
                          >
                            <el-input-number
                              style="width: 100%; margintop: 18px"
                              v-model.lazy="scope.row.largeUnitQty"
                              clearable
                              controls-position="right"
                              :precision="
                                scope.row.qtyOperateMode === 0 ||
                                scope.row.qtyOperateMode === 2
                                  ? 0
                                  : systemConfig.qty_show_precision
                              "
                              @change="
                                changeLarge(
                                  $event,
                                  `data.${scope.$index}.largeUnitQty`
                                )
                              "
                              :min="0"
                              :max="largeMax(scope.row)"
                            />
                          </el-form-item>
                          <div class="page-table-input-number-item-unite">
                            {{ scope.row.unitName }}
                          </div>
                        </div>
                        <div
                          class="page-table-input-number-item"
                          v-if="
                            scope.row.unitConvertCoefficient > 1 &&
                            scope.row.qtyOperateMode === 2
                          "
                        >
                          <el-form-item>
                            <el-input-number
                              style="width: 100%; margintop: 18px"
                              v-model.lazy="scope.row.smallUnitQty"
                              clearable
                              controls-position="right"
                              :precision="0"
                              :min="0"
                              :max="smallMax(scope.row)"
                            />
                          </el-form-item>
                          <div class="page-table-input-number-item-unite">
                            {{ scope.row.calcUnitName }}
                          </div>
                        </div>
                      </div>
                      <div
                        class="page-table-input-number-right"
                        v-if="scope.row.qtyOperateMode === 2"
                      >
                        {{ $fn.qtyFormatter(scope.row.qty) }}
                      </div>
                    </div>
                  </el-form-item>
                </template>
                <template v-slot:col-price="scope">
                  <p>{{ scope.row.price }}</p>
                  <p
                    style="color: red"
                    v-if="
                      scope.row.isLimitPrice == 1 &&
                      scope.row.price > scope.row.purchaseLimitPrice
                    "
                  >
                    超过产品限价:{{ scope.row.purchaseLimitPrice }}
                  </p>
                </template>
              </page-table>
            </el-form>
          </div>

          <!-- 选择产品 -->
          <NewSelectProduct
            v-if="productInfo.visible"
            v-model:show-dialog="productInfo.visible"
            :query="productInfo.query.queryMap"
            :query-params="productInfo.query.queryParams"
            :api="productInfo.api"
            :notDefaultProductSupplier="true"
            :showPrice="proxy.$permission('purchOrder:price')"
            :table-key="productInfo.tableKey"
            @callback="selectProductCallback"
          />
          <SetPreferenceNoQuery
            v-if="preferenceInfo.visible"
            v-model:visible="preferenceInfo.visible"
            :searchList="filterInfo.searchList"
            :fieldList="tableInfo.fieldList"
            :customizeUserVO="filterInfo.query.customizeUserVO"
            :groupLevelShow="false"
            @callback="setPreferenceCallback"
          />
        </div>
      </div>
    </NewFullScreen>
  </div>
</template>

<script setup name="purchOrderModify">
import {
  
} from '@/api/purch'
import {
  getCoreSystemConfigGetConfigValue,
  getProductCustomizeList,
} from '@/api/core'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
import _ from 'lodash'
const SetPreferenceNoQuery = defineAsyncComponent(() =>
  import('@/components/SetPreference/setPreferenceNoQuery')
)
const emits = defineEmits()
const { proxy } = getCurrentInstance()
const props = defineProps([
  'tableKey',
  'visible',
  'title',
  'orderId',
  'isSpecialEdit',
  'isCopy',
  'purchAccording',
])

const formRefs = ref([])

// 过滤相关配置
const filterInfo = ref({
  sortArr: [],
  copyQueryMap: {},
  query: {
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
    },
    queryParams: {
      purchAccording: '',
    },
  },
  list: [
    { type: 'slot', label: '添加产品', value: 'addProduct' },
    { type: 'slot', label: '删除产品', value: 'removeProduct' }
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  selections: [],
  selectionsCopy: [],
  summaryFieldList: [
    { value: 'qty', formatter: proxy.$fn.qtyFormatter },
    { value: 'price', show: 'false' },
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  fieldList: [],
  applicationFieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '150',
    btList: [
      {
        label: '删除产品',
        event: removeProduct,
        show: true,
        ifRender: ifRenderRemoveValue,
      },
    ],
  },
})
const fullInfo = ref({
  btnList: [{ label: '保存', event: save, show: true }],
})
//选择产品相关
const productInfo = ref({
  visible: false,
  api: getProductCustomizeList,
  tableKey:
    'productPageForPurchOrder-com.slip.spd.entity.vo.core.CoreProductVONew',
  query: {
    queryMap: {
      id: {
        queryType: 'NOT_IN',
        queryCategory: 'AND',
        value: null,
      },
      status: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
      supplierId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
      productId: {
        queryType: 'NOT_IN',
        queryCategory: 'AND',
        value: null,
      },
      putShelfStatus: {
        asTbName: 'core_product_new',
        columnName: 'put_shelf_status',
        queryResource: 0,
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: 1,
      },
      type: {
        asTbName: 'core_product_new',
        columnName: 'type',
        queryResource: 0,
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: 0,
      },
      isConsignment: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: '',
      },
    },
    queryParams: {
      checkDeptProduct: 1,
      selectStockTotalQty: 1,
    },
  },
  searchList: [],
})

const preferenceInfo = ref({
  visible: false,
})
const systemConfig = ref(proxy.$store.state.permission.systemConfig)
const licencesSystemConfig = ref('')

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emits('update:visible', newValue) // 更新父组件visible
  },
})
const canRemoveProduct = computed(() => {
  return tableInfo.value.selections.length && props.isSpecialEdit !== 1
})

watch(
  () => tableInfo.value.data,
  () => {
    tableInfo.value.data.forEach((row) => {
      let smallUnitQty = parseFloat(row.smallUnitQty || 0)
      let unitConvertCoefficient = parseFloat(row.unitConvertCoefficient || 1)
      let largeUnitQty = parseFloat(row.largeUnitQty || 0)
      let calcQty = proxy.$fn.accAdd(
        proxy.$fn.accMul(largeUnitQty, unitConvertCoefficient),
        smallUnitQty
      )
      let qty = proxy.$fn.qtyFormatter(
        proxy.$fn.accDiv(calcQty, unitConvertCoefficient)
      )
      row['calcQty'] = calcQty
      row['qty'] = qty
      row.sumAmount = proxy.$fn.accMul(
        proxy.$fn.accAdd(
          proxy.$fn.accDiv(smallUnitQty, unitConvertCoefficient),
          largeUnitQty
        ),
        parseFloat(row.price == null ? 0 : row.price)
      )
    })
  },
  {
    deep: true,
  }
)

onMounted(() => {
  getValueList()
})

setData()
function setData() {
  let obj = {
    qty: {
      label: '申购数量',
      value: 'qty',
      type: 'slot',
      minWidth: '250px',
      hidden: true,
    },
    price: {
      label: '单价',
      value: 'price',
      type: 'slot',
      formatter: proxy.$fn.TripartiteMethod,
      permission: !proxy.$permission('purchOrder:price'),
      hidden: true,
    },
    sumAmount: {
      label: '总金额',
      value: 'sumAmount',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
      permission: !proxy.$permission('purchOrder:price'),
      hidden: true,
    },
    defaultSupplierPrice: {
      label: '默认供应商价格',
      value: 'defaultSupplierPrice',
      type: 'column',
      permission: !proxy.$permission('purchOrder:price'),
      formatter: proxy.$fn.TripartiteMethod,
      hidden: true,
    },
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...obj,
  })
  getCustomize()
}
function ifRenderRemoveValue() {
  return props.isSpecialEdit !== 1
}

function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(true)
    }
  })
}
function changeLarge(e, str) {
  proxy.$refs.tableForm.clearValidate(str)
}
function largeMax(row) {
  if (
    systemConfig.value.use_convert_count_restrict == 1 &&
    (row.maxConvertCount || row.maxConvertCount === 0)
  ) {
    return parseInt((row.maxConvertCount || 0) / row.unitConvertCoefficient)
  } else {
    return 99999999
  }
}
function smallMax(row) {
  if (
    systemConfig.value.use_convert_count_restrict == 1 &&
    (row.maxConvertCount || row.maxConvertCount === 0)
  ) {
    return parseInt((row.maxConvertCount || 0) % row.unitConvertCoefficient)
  } else {
    return row.unitConvertCoefficient - 1
  }
}
// 触发事件
function handleEvent(event, data) {
  const _tableInfo = tableInfo.value
  switch (event) {
    case 'tableCheck':
      _tableInfo.selections = [...data]
      break
  }
}

//添加产品按钮
function addProduct() {
  const _tableInfo = tableInfo.value
  let idNotIn = _tableInfo.data.map(function (item) {
    return item.productId
  })
  productInfo.value.query.queryMap.id.value = idNotIn.toString()
  productInfo.value.query.queryMap.status.value = 1
  productInfo.value.visible = true
}

function selectProductCallback(rows) {
  tableInfo.value.data = rows.concat(tableInfo.value.data)
}

//删除产品
function removeProduct(item) {
  if (item) {
    tableInfo.value.data = tableInfo.value.data.filter(
      (obj) => obj.productId !== item.productId
    )
    return
  }
  proxy
    .$confirm('删除后将改变数据,是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      tableInfo.value.selectionsCopy = proxy.$fn.deepClone(
        tableInfo.value.selections
      )
      tableInfo.value.data = tableInfo.value.data.filter(
        (row) => !tableInfo.value.selections.includes(row)
      )
    })
}

function save() {
  const _tableInfo = tableInfo.value
  proxy.$fn.checkForm(formRefs.value).then(() => {
    if (!_tableInfo.data.length) {
      proxy.$message({
        duration: 3500,
        type: 'warning',
        showClose: true,
        message: '产品不能为空',
      })
      return
    }
    let newDetails = _tableInfo.data.filter((item) => item.calcQty > 0)
    if (newDetails.length < _tableInfo.data.length) {
      proxy
        .$confirm(`存在数量为0的产品，是否继续保存`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
        .then(() => {
          checkSave()
        })
        .catch()
    } else {
      checkSave()
    }
  })
}
function checkSave() {
  
}
function getPurchOrderById(orderId) {
  
}

function getValueList() {
  getCoreSystemConfigGetConfigValue({
    systemConfigCode: 'license_nearly_effective',
  }).then((resp) => {
    if (resp && resp.success) {
      licencesSystemConfig.value = resp.data
    }
  })
}
function tableRowClassName({ row = undefined }) {
  if (row.licenseEndDate) {
    let dataDiff = proxy.$fn.dateDiffLicen(row.licenseEndDate)
    if (dataDiff <= 0) {
      return 'expire-row'
    } else if (Number(licencesSystemConfig.value) >= dataDiff) {
      return 'nearly-row'
    }
  }
  return ''
}
function tableCellClassName({ column, row }) {
  if (row.calcQty === 0 && column.property === 'qty') {
    return 'cell-color'
  }
  return ''
}
function getCustomize(update = undefined) {
  let _tableInfo = tableInfo.value
  let param = {
    tableKey: props.tableKey,
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      _tableInfo.fieldList = proxy.$fn.setFieldList(
        _tableInfo.fieldList,
        data.detail
      )

      filterInfo.value.query.customizeUserVO = data
      filterInfo.value.query.queryMap.orderId.value = props.orderId
      if (update) {
        let arr = []
        for (let key in data.detail) {
          arr.push(data.detail[key])
        }
        let sortArr = []
        arr.forEach((item) => {
          if (item.sortControllerType === 1) {
            sortArr.push({
              prop: item.fieldName,
              order: 'ascending',
            })
          } else if (item.sortControllerType === 2) {
            sortArr.push({
              prop: item.fieldName,
              order: 'descending',
            })
          }
        })
        if (sortArr.length) {
          proxy.$refs.table.$refs.table.sort(sortArr[0].prop, sortArr[0].order)
        }
        return
      }
      if (props.orderId) {
        getPurchOrderById(props.orderId)
      }
    }
  })
}
</script>

<style scoped lang="scss">
.model-panel-title {
  display: flex;
  align-items: center;
}
:deep(.el-table) {
  .nearly-row {
    background: #fceacb;
  }
  .expire-row {
    background: #f5e4e4;
  }
  .cell-color {
    background: #f4aed9bd;
  }
}
</style>
